<template>

  <div>

    <div class="u-box">
      <div class="left">
        <el-card style="height: calc(100vh - 124px); overflow-y: auto">
          <depart-tree-show @clear="departClear" @select="departSelect" />
        </el-card>
      </div>

      <div class="right" style="overflow-x: auto">
        <data-table
          ref="dataTable"
          :options="options"
          :list-query="listQuery"
          @add="handleAdd"
          @edit="handleUpdate"
          @multi-actions="handleMultiActions"
        >

          <template #filter-content>

            <el-button-group class="filter-item" size="small">
              <el-button v-permission="['sys:user:import']" icon="el-icon-upload2" size="small" @click="showImport">导入</el-button>
              <el-button v-permission="['sys:user:export']" icon="el-icon-download" size="small" @click="exportExcel">导出</el-button>
              <el-button v-permission="['sys:user:import']" icon="el-icon-user" size="small" @click="showBatchFace">导入人脸</el-button>
            </el-button-group>

            <div style="width: 100%; margin-top: 10px">
              <role-select v-model="listQuery.params.roleIds" style="width: 200px;" class="filter-item" />
              <group-select v-model="listQuery.params.groupIds" style="width: 200px;" class="filter-item"/>
              <dic-list-select v-model="listQuery.params.state" dic-code="user_state" style="width: 100px;" title="用户状态"/>
              <el-input v-model="listQuery.params.userName" class="filter-item" size="small" style="width: 150px;" placeholder="搜索登录名或姓名" />
              <el-input v-model="listQuery.params.idCard" class="filter-item" size="small" style="width: 150px;" placeholder="身份证号" />
              <el-input v-model="listQuery.params.mobile" class="filter-item" size="small" style="width: 150px;" placeholder="手机号码" />
            </div>

          </template>

          <template #data-columns>

            <el-table-column
              type="selection"
              width="55"
            />

            <el-table-column
              show-overflow-tooltip
              align="center"
              label="账号"
              prop="userName"
            >

              <template v-slot="scope">
                <detail-link :id="scope.row.id" :title="scope.row.userName" permission="sys:user:update" @click="handleUpdate" />
              </template>

            </el-table-column>

            <el-table-column
              show-overflow-tooltip
              align="center"
              label="姓名"
              prop="realName"
            />

            <el-table-column
              align="center"
              label="手机号"
              prop="mobile"
            />


            <el-table-column
              show-overflow-tooltip
              align="center"
              label="归属部门"
              prop="deptCode_dictText"
            />

            <el-table-column
              show-overflow-tooltip
              align="center"
              label="所在群组"
              prop="groupNames"
            />

            <el-table-column
              show-overflow-tooltip
              align="center"
              label="用户角色"
              prop="roleNames"
            />


            <el-table-column
              show-overflow-tooltip
              align="center"
              label="实名认证">

              <template v-slot="scope">
                <el-link v-if="scope.row.realPerson" type="primary" @click="showImage(scope.row.face)">已认证</el-link>
                <span v-else>未认证</span>
              </template>
            </el-table-column>

            <el-table-column
              show-overflow-tooltip
              align="center"
              label="注册时间"
              prop="createTime"
            />

            <el-table-column
              show-overflow-tooltip
              align="center"
              label="到期时间"
              prop="expireTime">
              <template v-slot="scope">
                <span v-if="!scope.row.expireTime">永久有效</span>
                <span v-else>{{ scope.row.expireTime }}</span>
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              label="状态"
              width="100px"
              prop="state_dictText"
            />

            <el-table-column
              v-if="checkPermission(['sys:user:points'])"
              align="center"
              label="积分"
              width="100px"
              prop="points"
              sortable="custom"
            >

              <template v-slot="scope">
                <el-link v-permission="['sys:user:points']" type="primary" icon="el-icon-coin" @click="naviToPoints(scope.row.id)">{{ scope.row.points }}</el-link>
              </template>
            </el-table-column>

          </template>
        </data-table>
      </div>

    </div>

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="importVisible"
      title="导入用户"
      width="30%"
    >

      <el-row>

        <import-excel
          :data="{}"
          title="用户"
          action="/api/sys/user/import"
          template="/api/sys/user/import/template"
          @success="importSuccess"
        />

      </el-row>

    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="importFaceVisible"
      title="人脸导入"
      width="30%"
    >

      <face-upload :data="{}" @success="fillSuccess"/>

    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="deptVisible"
      title="批量修改部门"
      width="30%">

      <depart-tree-select v-model="batchDeptForm.deptCode" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="deptVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="saveBatchDept">确 定</el-button>
      </div>

    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="roleVisible"
      :title="batchRoleForm.flag===1?'批量分配角色':'批量移除角色'"
      width="30%"
    >

      <role-select v-model="batchRoleForm.roleIds" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="saveBatchRole">确 定</el-button>
      </div>

    </el-dialog>


    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="groupVisible"
      :title="batchGroupForm.flag===1?'批量加入群组':'批量移除群组'"
      width="30%"
    >

      <group-select v-model="batchGroupForm.groupIds" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="groupVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="saveBatchGroup">确 定</el-button>
      </div>

    </el-dialog>


    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="expireVisible"
      title="批量设置到期时间"
      width="30%"
    >

      <div style="padding-top: 10px">
        <el-date-picker
          v-model="batchExpireForm.expireTime"
          size="small"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 100%"
        />
      </div>


      <div slot="footer" class="dialog-footer">
        <el-button @click="expireVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="saveBatchExpire">确 定</el-button>
      </div>

    </el-dialog>


    <el-dialog
      :visible.sync="imageVisible"
      title="人脸照片"
      width="30%">
      <div style="display: flex; align-items: center; justify-content: center">
        <el-image :src="imageUrl"/>
      </div>

    </el-dialog>

    <user-update-dialog :user-id="postForm.id" :depart-id="postForm.departId" :visible.sync="dialogVisible"/>

  </div>

</template>

<script>
import { exportExcel, apiBatchDept, apiBatchRole, apiBatchExpire } from '@/api/sys/user/user'
import { batchJoin } from '@/api/sys/group/user'
import permission from '@/directive/permission'
import { mapGetters } from 'vuex'
import checkPermission from '@/utils/permission'
import MobileBinder from '@/views/admin/sys/user/components/MobileBinder'
import FaceUpload from '@/views/admin/sys/user/components/FaceUpload.vue'
import UserUpdateDialog from '@/views/admin/sys/user/components/UserUpdateDialog/index.vue'
import DepartTreeShow from '@/views/admin/sys/depart/components/DepartTreeShow/index.vue'
import GroupSelect from '@/components/GroupSelect/index.vue'

export default {
  name: 'SysUser',
  directives: { permission },
  components: { GroupSelect, DepartTreeShow, UserUpdateDialog, FaceUpload, MobileBinder },
  filters: {

    // 订单状态
    userState(value) {
      const map = {
        '0': '正常',
        '1': '禁用'
      }
      return map[value]
    }
  },
  props: {
    roleIds: Array
  },
  data() {
    return {

      loading: false,
      importVisible: false,
      importFaceVisible: false,
      dialogVisible: false,

      listQuery: {
        current: 1,
        size: 10,
        params: {
          roleId: '',
          deptCode: ''
        }
      },

      postForm: {},
      options: {

        add: {
          enable: true,
          permission: 'sys:user:add'
        },
        edit: {
          enable: true,
          permission: 'sys:user:update'
        },
        delete: {
          enable: true,
          permission: 'sys:user:delete',
          url: '/api/sys/user/delete'
        },

        // 列表请求URL
        listUrl: '/api/sys/user/paging',
        // 批量操作列表
        multiActions: [
          {
            value: 'enable',
            label: '启用',
            url: '/api/sys/user/state',
            permission: 'sys:user:state'
          }, {
            value: 'disable',
            label: '禁用',
            url: '/api/sys/user/state',
            permission: 'sys:user:state'
          },
          {
            value: 'state',
            label: '批量通过审核',
            state: 0,
            url: '/api/sys/user/state',
            permission: 'sys:user:state'
          }, {
            value: 'state',
            label: '标记为待审核',
            state: 2,
            url: '/api/sys/user/state',
            permission: 'sys:user:state'
          },

          {
            value: 'changeDept',
            label: '批量设置部门',
            permission: 'sys:user:batch-dept'
          }, {
            value: 'clearDept',
            label: '批量清除部门',
            permission: 'sys:user:batch-dept'
          }, {
            value: 'changeRole',
            label: '批量分配角色',
            permission: 'sys:user:batch-role'
          }, {
            value: 'clearRole',
            label: '批量移除角色',
            permission: 'sys:user:batch-role'
          }, {
            value: 'changeGroup',
            label: '批量设置群组',
            permission: 'sys:user:batch-group'
          }, {
            value: 'clearGroup',
            label: '批量移除群组',
            permission: 'sys:user:batch-group'
          }, {
            value: 'batchExpire',
            label: '批量设置到期时间',
            permission: 'sys:user:batch-expire'
          }
        ]
      },

      deptVisible: false,
      batchDeptForm: {
        deptCode: '',
        userIds: []
      },
      roleVisible: false,
      batchRoleForm: {
        roleIds: [],
        userIds: []
      },
      imageVisible: false,
      imageUrl: '',

      // 群组管理
      groupVisible: false,
      batchGroupForm: {
        groupIds: [],
        userIds: []
      },

      // 批量设置到期
      expireVisible: false,
      batchExpireForm: {
        expireTime: '',
        userIds: []
      }


    }
  },
  computed: {
    ...mapGetters([
      'siteData'
    ])
  },

  watch: {
    roleIds: {
      handler(val) {
        this.listQuery.params.roleIds = val
      }
    },
    // 关闭窗口刷新
    dialogVisible: {
      handler(val) {
        if (!val) {
          this.$refs.dataTable.getList()
          this.$refs.dataTable.clearSelection()
        }
      }
    }
  },

  activated() {
    this.$refs.dataTable.refresh()
  },

  created() {
    const departId = this.$route.params.departId
    if (departId !== undefined) {
      this.listQuery.params.departId = departId
    }

    if (this.roleIds != null && this.roleIds.length > 0) {
      this.listQuery.params.roleIds = this.roleIds
    }
  },

  methods: {

    checkPermission,

    // 添加用户
    handleAdd() {
      this.postForm = { id: '', departId: this.postForm.departId }
      this.dialogVisible = true
    },

    // 修改用户
    handleUpdate(id) {
      this.postForm = { id: id }
      this.dialogVisible = true
    },

    departSelect(data) {
      this.departChange(data.id, data.deptCode)
    },

    departClear() {
      this.departChange('', '')
    },

    departChange(id, code) {
      this.postForm.departId = id
      this.listQuery.params.deptCode = code
    },

    exportExcel() {
      // 导出当前查询的数据
      exportExcel(this.listQuery.params)
    },

    showImport() {
      this.importVisible = true
    },

    importSuccess() {
      this.importVisible = false
      this.$refs.dataTable.getList()
    },

    fillSuccess() {
      this.importFaceVisible = false
      this.$refs.dataTable.getList()
    },

    naviToPoints(id) {
      this.$router.push({ name: 'UserPoints', params: { id: id }})
    },

    handleMultiActions(event) {
      if (event.opt === 'changeDept') {
        this.deptVisible = true
        this.batchDeptForm.flag = 1
        this.batchDeptForm.userIds = event.ids
      }

      if (event.opt === 'clearDept') {
        this.batchDeptForm.deptCode = ''
        this.batchDeptForm.userIds = event.ids
        this.saveBatchDept()
      }

      if (event.opt === 'changeRole') {
        this.roleVisible = true
        this.batchRoleForm.flag = 1
        this.batchRoleForm.userIds = event.ids
      }

      if (event.opt === 'clearRole') {
        this.roleVisible = true
        this.batchRoleForm.flag = 0
        this.batchRoleForm.userIds = event.ids
      }

      if (event.opt === 'changeGroup') {
        this.groupVisible = true
        this.batchGroupForm.flag = 1
        this.batchGroupForm.userIds = event.ids
      }

      if (event.opt === 'clearGroup') {
        this.groupVisible = true
        this.batchGroupForm.flag = 0
        this.batchGroupForm.userIds = event.ids
      }

      if (event.opt === 'batchExpire') {
        this.expireVisible = true
        this.batchExpireForm.userIds = event.ids
      }
    },

    saveBatchDept() {
      this.loading = true
      apiBatchDept(this.batchDeptForm).then(() => {
        this.$message({
          type: 'success',
          message: '批量操作用户部门成功!'
        })

        this.batchDeptForm.deptCode = ''
        this.deptVisible = false
        this.$refs.dataTable.getList()
        this.$refs.dataTable.clearSelection()
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    saveBatchRole() {
      this.loading = true
      apiBatchRole(this.batchRoleForm).then(() => {
        this.$message({
          type: 'success',
          message: '批量操作用户角色成功!'
        })

        this.batchRoleForm.roleIds = []

        this.loading = false
        this.roleVisible = false
        this.$refs.dataTable.getList()
        this.$refs.dataTable.clearSelection()
      }).catch(() => {
        this.loading = false
      })
    },

    saveBatchGroup() {
      this.loading = true
      batchJoin(this.batchGroupForm).then(() => {
        this.$message({
          type: 'success',
          message: '批量群组操作成功!'
        })

        this.batchGroupForm.groupIds = []
        this.loading = false
        this.groupVisible = false
        this.$refs.dataTable.getList()
        this.$refs.dataTable.clearSelection()
      }).catch(() => {
        this.loading = false
      })
    },

    saveBatchExpire() {
      this.loading = true
      apiBatchExpire(this.batchExpireForm).then(() => {
        this.$message({
          type: 'success',
          message: '批量设置到期时间成功!'
        })

        this.batchExpireForm.expireTime = ''

        this.loading = false
        this.expireVisible = false
        this.$refs.dataTable.getList()
        this.$refs.dataTable.clearSelection()
      }).catch(() => {
        this.loading = false
      })
    },


    showBatchFace() {
      this.importFaceVisible = true
    },

    showImage(url) {
      this.imageUrl = url
      this.imageVisible = true
    }
  }
}
</script>

<style scoped>
.u-box{
  display: flex;
}

.u-box > .left{
  width: 300px;
}

.u-box > .right{
  flex-grow: 1;
  padding-left: 20px
}
</style>
